package com.jifeng.br.pjj.bookreader.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Producer;
import com.jifeng.br.pjj.bookreader.entity.CodeEntity;
import com.jifeng.br.pjj.bookreader.mapper.CodeMapper;
import com.jifeng.br.pjj.bookreader.service.CodeService;
import com.jifeng.br.pjj.bookreader.util.MsgUtil;
import com.jifeng.br.pjj.bookreader.util.exception.RTException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Random;

/**
 * @Author PangJunjie
 * @Date 2023/7/11/011
 */
@Service
@Transactional
public class CodeServiceImpl extends ServiceImpl<CodeMapper, CodeEntity> implements CodeService {
    @Autowired
    private Producer producer;

    @Override
    public BufferedImage getKaptcha(String uuid) {
        if (StringUtils.isEmpty(uuid)) {
            throw new RTException("uuid不能为空!");
//            RTException rt = new RTException();
//            rt.setCode(500);
//            rt.setMsg("uuid不能为空");
//            throw rt;
        }
        /*生成验证码文字*/
        String code = producer.createText();
        /*获取日期对象*/
        Date date = new Date();
        //设置2分钟有效
        date.setMinutes(date.getMinutes() + 2);
        /*初始化验证码类*/
        CodeEntity codeEntity = new CodeEntity();
        codeEntity.setUuid(uuid);
        codeEntity.setCode(code);
        codeEntity.setExpires(date);
        /*保存验证码信息到数据库*/
        this.save(codeEntity);
        return producer.createImage(code);
    }

    @Override
    public boolean checkKaptcha(String uuid, String code) {
        CodeEntity codeEntity = this.getById(uuid);
        /*每次验证无论成功与否都会根据uuid进行删除*/
        this.removeById(uuid);
        return codeEntity != null && code.equalsIgnoreCase(codeEntity.getCode()) && codeEntity.getExpires().getTime() > System.currentTimeMillis();
    }

    @Override
    public void sendMsg(String phone, String uuid) {
        String code = getMsgCode();
        MsgUtil.print(phone, "#code#=" + code);
        CodeEntity codeEntity = new CodeEntity();
        codeEntity.setCode(code);
        codeEntity.setUuid(uuid);
        /*获取日期对象*/
        Date date = new Date();
        //设置2分钟有效
        date.setMinutes(date.getMinutes() + 5);
        codeEntity.setExpires(date);
        this.save(codeEntity);
    }

    private String getMsgCode() {
        String code = "";
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            int r = random.nextInt(10);
            code += r;
        }
        return code;
    }
}
